import 'dart:math';

import 'package:flutter/material.dart';

///**
///* @author hrongyong
///* @date   2/4/21
///* @email hrongyong@gmail.com
///* Description: 圆形水滴 - 没有动画的
///*/
class RoundWaterDropChartPainter extends CustomPainter {
  ///上标
  String superscript;

  Color superscriptColor;

  ///中间
  String middle;
  Color middleColor;

  ///下标
  String subscript;
  Color subscriptColor;

  ///主题颜色
  Color themeColor;

  ///最大半径
  double maxRadius = 0.0;

  ///中心圆半径
  double centerCircleRadius = 0.0;

  ///上中下标大小
  final double fontSize;

  ///文字
  final TextPainter _textPainter = TextPainter(textDirection: TextDirection.ltr);

  RoundWaterDropChartPainter({
    @required this.superscript,
    @required this.middle,
    @required this.subscript,
    @required this.themeColor,
    this.superscriptColor = const Color(0xFFC64545),
    this.middleColor = Colors.white,
    this.subscriptColor = const Color(0xFF000000),
    this.fontSize = 4,
  });

  Paint themePaint = Paint()..isAntiAlias = true;

  @override
  void paint(Canvas canvas, Size size) {
    themePaint..color = themeColor;
    maxRadius = min(size.width / 2, size.height / 2);
    centerCircleRadius = maxRadius * 0.9;
    canvas.translate(size.width / 2, size.height / 2);
    canvas.drawCircle(Offset.zero, maxRadius, themePaint..style = PaintingStyle.stroke);
    canvas.drawCircle(Offset.zero, centerCircleRadius, themePaint..style = PaintingStyle.fill);

    //绘制文字
    drawText(canvas, size);
  }

  void drawText(Canvas canvas, Size size) {
    ///绘制上标
    TextSpan superscriptText = TextSpan(text: superscript, style: TextStyle(fontSize: fontSize + 1, color: superscriptColor));
    _textPainter.text = superscriptText;
    _textPainter.layout(); // 进行布局
    Size superscriptTextSize = _textPainter.size;
    Offset superscriptTextOffsetPos = Offset(-superscriptTextSize.width / 2, -centerCircleRadius / 2 - superscriptTextSize.height / 2);
    _textPainter.paint(canvas, superscriptTextOffsetPos);

    ///绘制中间
    TextSpan middleText = TextSpan(text: middle, style: TextStyle(fontSize: fontSize, color: middleColor));
    _textPainter.text = middleText;
    _textPainter.layout(); // 进行布局
    Size middleTextSize = _textPainter.size;
    Offset textOffsetPos = Offset(-middleTextSize.width / 2, -middleTextSize.height / 2);
    _textPainter.paint(canvas, textOffsetPos);

    ///绘制下标
    TextSpan subscriptText = TextSpan(text: subscript, style: TextStyle(fontSize: fontSize + 1, color: subscriptColor));
    _textPainter.text = subscriptText;
    _textPainter.layout(); // 进行布局
    Size subscriptTextSize = _textPainter.size;
    Offset subscriptTextOffsetPos = Offset(-subscriptTextSize.width / 2, centerCircleRadius / 2 - subscriptTextSize.height / 2);
    _textPainter.paint(canvas, subscriptTextOffsetPos);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
